package sing.core.weight

import android.content.Context
import android.graphics.Rect
import android.graphics.drawable.Drawable
import android.util.AttributeSet
import android.view.MotionEvent
import android.view.View
import android.view.View.OnFocusChangeListener
import androidx.appcompat.widget.AppCompatEditText
import androidx.core.content.ContextCompat
import sing.core.R
import sing.core.ext.util.dp2px
import sing.core.ext.view.afterTextChange

class EditTextWithDelete : AppCompatEditText, OnFocusChangeListener {
    private var drawable: Drawable? = null
    private var mContext: Context? = null
    private var tmpEditText: AppCompatEditText? = null
    private var focused = false

    constructor(context: Context?) : super(context!!) {
        init()
    }

    constructor(context: Context, attrs: AttributeSet?) : super(context, attrs) {
        init(context, attrs)
    }

    constructor(context: Context, attrs: AttributeSet?, defStyle: Int) : super(context, attrs, defStyle) {
        init(context, attrs)
    }

    private fun init(context: Context, attrs: AttributeSet?) {
        mContext = context
        val attributes = context.obtainStyledAttributes(attrs, R.styleable.EditTextWithDelete)
        drawable = attributes.getDrawable(R.styleable.EditTextWithDelete_delSrc)
        attributes.recycle()
        init()
    }

    private fun init() {
        if (drawable == null) {
            drawable = ContextCompat.getDrawable(mContext!!, R.drawable.ic_delete_gray)
        }

        onFocusChangeListener = this
        afterTextChange {  setDrawable() }
    }

    override fun onFocusChange(v: View, hasFocus: Boolean) {
        focused = hasFocus
        if (focused && length() > 0) {
            setCompoundDrawablesWithIntrinsicBounds(null, null, drawable, null)
        } else {
            setCompoundDrawablesWithIntrinsicBounds(null, null, null, null)
        }
    }

    override fun onFocusChanged(focused: Boolean, direction: Int, previouslyFocusedRect: Rect?) {
        super.onFocusChanged(focused, direction, previouslyFocusedRect)
        this.focused = focused
        if (focused && length() > 0) {
            setDrawable()
            setCompoundDrawablesWithIntrinsicBounds(null, null, drawable, null)
        } else {
            setCompoundDrawablesWithIntrinsicBounds(null, null, null, null)
        }
    }

    private fun setDrawable() {
        if (length() <= 0 || !focused) {
            setCompoundDrawablesWithIntrinsicBounds(null, null, null, null)
        } else {
            drawable!!.setBounds(0, 0, dp2px(15), dp2px(15))
            setCompoundDrawables(null, null, drawable, null)
        }
    }

    override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec)
        setDrawable()
    }

    override fun onTouchEvent(event: MotionEvent): Boolean {
        if (drawable != null && event.action == MotionEvent.ACTION_UP) {
            val x = event.x.toInt()
            //判断触摸点是否在水平范围内
            val isInnerWidth = x > width - totalPaddingRight && x < width - paddingRight
            //获取删除图标的边界，返回一个Rect对象
            val rect = drawable!!.bounds
            //获取删除图标的高度
            val height = rect.height()
            val y = event.y.toInt()
            //计算图标底部到控件底部的距离
            val distance = (getHeight() - height) / 2
            //判断触摸点是否在竖直范围内(可能会有点误差)
            //触摸点的纵坐标在distance到（distance+图标自身的高度）之内，则视为点中删除图标
            val isInnerHeight = y > distance && y < distance + height
            if (isInnerWidth && isInnerHeight) {
                setText("")
                if (tmpEditText != null) tmpEditText!!.setText("")
            }
        }
        return super.onTouchEvent(event)
    }

    fun setTmpEditText(tmpEditText: AppCompatEditText?) {
        this.tmpEditText = tmpEditText
    }
}